﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Data.Odbc;
using _0812159_0812164.dao;
using System.Collections.Generic;
using _0812159_0812164.pojo;
using System.Web.Script.Serialization;

namespace _0812159_0812164
{
    public partial class _Default : System.Web.UI.Page
    {
        protected String returnValue;
        protected void Page_Load(object sender, EventArgs e)
        {
            String action = Request.Headers["action"];
            switch (action)
            {
                case "add":
                    addLocation();
                    break;
                case "edit":
                    editLocation();
                    break;
                case "del":
                    deleteLocation();
                    break; 
                case "search":
                    searchLocation();
                    break;
                case "login":
                    doLogin();
                    break;
                case "logout":
                    doLogout();
                    break;
                case "reloadtree":
                    doReloadTreeLocation();
                    break;
                case "share":
                    shareLocation();
                    break;
                case "checkshare":
                    checkShareLocation();
                    break;
                case "deny":    //deny a share location
                    denyShareLocation();
                    break;
                case "accept":  //accept a share location
                    acceptShareLocation();
                    break;

            }
            InitForm();
        }

        private void InitForm()
        {
            List<Category> lCataBase = CategoryDAO.getListCategory();
            listCatalog.Items.Clear();
            foreach (Category cate in lCataBase)
            {
                ListItem lItem = new ListItem(cate.Namecategory, cate.Idcategory.ToString());
                listCatalog.Items.Add(lItem);
                ddlCatelogy2.Items.Add(lItem);
            }
            ListItem all = new ListItem("--- All ---", "-1");
            ddlCatelogy2.Items.Insert(0, all);

            List<User> lUser = UserDAO.getListUser();
            ddlUserShare.Items.Clear();
            foreach (User user in lUser)
            {
                ListItem lItem = new ListItem(user.Username, user.Username);
                ddlUserShare.Items.Add(lItem);                
            }

            ListItem item = new ListItem("1", "1"); ddlNumOfResults.Items.Add(item);
            item = new ListItem("5", "5"); ddlNumOfResults.Items.Add(item);
            item = new ListItem("10", "10"); ddlNumOfResults.Items.Add(item);
            item = new ListItem("20", "20"); ddlNumOfResults.Items.Add(item);
            item = new ListItem("50", "50"); ddlNumOfResults.Items.Add(item);
            item = new ListItem("100", "100"); ddlNumOfResults.Items.Add(item);
            ddlNumOfResults.SelectedValue = "10";
        }

        private void doLogin()
        {
            String username = Request["u"];
            String pass = Request["p"];
            User user = UserDAO.kiemtradangnhap(username, pass);
            Response.ContentType = "text/xml";
            string strXML = "false";
            if (user.Username != null && user.Username != "")
            {
                Session["username"] = user.Username;
                strXML = user.Username;
            }

            Response.Write(strXML);
            Response.End();
        }
        private void doLogout()
        {
            Session.Remove("username");            
        }


        private void shareLocation()
        {
            string username = Session["username"].ToString();
            List<Share> ls = ShareDAO.getListShare(username);
            JavaScriptSerializer ser = new JavaScriptSerializer();
            string share = ser.Serialize(ls);

            int locaID = Int32.Parse(Request["id"].ToString());
            string userShared = Request["user"].ToString();
            string userShare = Session["username"].ToString();
            Share sh = new Share(userShare, userShared, locaID);

            string strXML = ShareDAO.InsertShare(sh).ToString();
            Response.Write(strXML);
            Response.End();
        }



        private void checkShareLocation()
        {
            string strXML = "";
            if (Session["username"] != null)
            {
                string username = Session["username"].ToString();
                List<Share> ls = ShareDAO.getListShare(username);
                if (ls.Count != 0)
                {
                    for (int i = 0; i < ls.Count; i++)
                    {
                        strXML += String.Format("<div class='item' id={0}>", ls[i].Id);
                        strXML += String.Format("<div class='info'>{0} chia sẻ địa điểm {1}</div>", ls[i].Src, LocationDAO.getInfo(ls[i].Location).Name);
                        strXML += String.Format("<div class='button right' onclick='javascript:deny({0})'>Bỏ qua</div>", ls[i].Id);
                        strXML += String.Format("<div class='button right' onclick='javascript:accept({0},{1})'>Chấp nhận</div>", ls[i].Id, ls[i].Location);
                        strXML += "</div>";
                    }
                }
                else
                    strXML = "false";
            }

            Response.Write(strXML);
            Response.End();
        }

        public void addLocation()
        {
            if (Session["username"] != null)
            {
                Location lc = new Location();
                lc.Username = Session["username"].ToString();
                lc.Name = Request["name"];
                lc.Address = Request["address"];
                lc.Description = Request["description"];
                lc.Idcategory = Convert.ToInt32(Request["idcategory"]);
                string latlng = Request["latlng"];
                string[] args = latlng.Split('(', ',', ')');
                lc.Latitude = (float)Convert.ToDouble(args[1]);
                lc.Longitude = (float)Convert.ToDouble(args[2]);
                // Gui du lieu ve client
                string strXML = LocationDAO.InsertInfo(lc).ToString() ; 
                Response.ContentType = "text/xml";
                Response.Write(strXML);
                Response.End(); 
            }
        }

        private void editLocation()
        {
            Location lc = new Location();
            lc.Username = Session["username"].ToString();
            lc.Idlocation = Convert.ToInt32(Request["id"]);
            lc.Name = Request["name"];
            lc.Address = Request["address"];
            lc.Description = Request["description"];
            lc.Idcategory = Convert.ToInt32(Request["idcategory"]);
            lc.Latitude = (float)Convert.ToDouble(Request["lat"]);
            lc.Longitude = (float)Convert.ToDouble(Request["lng"]);
            // Gui du lieu ve client
            string strXML = LocationDAO.UpdateInfo(lc).ToString(); 
            Response.ContentType = "text/xml";
            Response.Write(strXML);
            Response.End();
        }

        private void deleteLocation()
        {
            int idLocation = Convert.ToInt32(Request["id"]);
            // Gui du lieu ve client
            string strXML = LocationDAO.DeleteInfo(idLocation).ToString(); // chuỗi xml dữ liệu muốn truyền xuống Client
            Response.ContentType = "text/xml";
            Response.Write(strXML);
            Response.End(); // server response dữ liệu xuống theo định dạng XML 
        }

        private void doReloadTreeLocation()
        {
            string xmlTree = "";
            xmlTree += "<ul id=\"browser\" class=\"filetree treeview\">\n<li>";            
            List<Category> lCataBase = CategoryDAO.getListCategory();
            List<Location> lLocaBase = new List<Location>();

            string username = Request["username"];
            //username = Session["username"].ToString(); ;
            lLocaBase = LocationDAO.getListLocation(username);
            Category rootCate = new Category("Địa điểm", 1, 0);
            TreeNode rootNode = new TreeNode(rootCate.Namecategory, rootCate.Idcategory.ToString());

            Expant(rootCate.Idcategory, lCataBase, lLocaBase, ref xmlTree);
            xmlTree += "</ul>\n";

            Response.ContentType = "text/xml";
            Response.Write(xmlTree);
            Response.End();                      
        }

        public void searchLocation()
        {
            if (Session["username"] != null)
            {
                string username = Session["username"].ToString();
                string keyword = Request["keyword"];
                string catelogy = Request["catelogy"];                
                string numofresults = Request["numofresults"];                
                string latlng = Request["latlng"];
                string[] args = latlng.Split('(', ',', ')');

                int cate = int.Parse(catelogy);
                float lat = float.Parse(args[1]);
                float lng = float.Parse(args[2]);
                int num = int.Parse(numofresults);

                List<Location> lResults = LocationDAO.search(username, keyword, cate, lat, lng, num);

                // Gui du lieu ve client
                if (num > lResults.Count)
                    num = lResults.Count;
                string strXML = "<results>";
                for (int i = 0; i < num; i++)
                {
                    Location loca = lResults[i];
                    string link = "javascript:showMarket(" + loca.Idlocation.ToString() + "," + loca.Idcategory.ToString() + ",'" + loca.Name + "','" + loca.Address + "','" + loca.Description + "'," + loca.Latitude.ToString() + "," + loca.Longitude.ToString() + ")";
                    strXML += "<a href=\"" + link + "\">" + loca.Name + "</a><br/>";
                }
                strXML += "</results>";
                Response.ContentType = "text/xml";
                Response.Write(strXML);
                Response.End();
            }
        }

        // set state of idShare to -1;
        private void denyShareLocation()
        {
            string username = Session["username"].ToString();
            int idShare = Int32.Parse(Request["idshare"]);
            string strXML = ShareDAO.DeleteShare(idShare).ToString();
            Response.ContentType = "text/xml";
            Response.Write(strXML);
            Response.End();
        }

        // set state of idShare to 1 and
        // save shared location to location list of current user.
        private void acceptShareLocation()
        {
            string username = Session["username"].ToString();
            int idShare = Int32.Parse(Request["idshare"]);
            int idLocation = Int32.Parse(Request["idlocation"]);
            ShareDAO.AcceptShare(idShare);
            Location lc = LocationDAO.getInfo(idLocation);
            lc.Username = username;            
            string strXML = LocationDAO.InsertInfo(lc).ToString();
            Response.ContentType = "text/xml";
            Response.Write(strXML);
            Response.End();
        }

        private void Expant(int idCategory, List<Category> lCataBase, List<Location> lLocaBase, ref string xmlTree)
        {
            bool bHasChild = false;
            string xmlFolder = "";
            string xmlFiles = "";

            List<Category> lChild = CategoryDAO.getListCategoryChild(idCategory, lCataBase);
            if (lChild.Count != 0)
            {
                bHasChild = true;
                xmlFolder += "<ul>\n";
                
                foreach (Category cate in lChild)
                {
                    xmlFolder += "<li><span class=\"folder\">";
                    xmlFolder += cate.Namecategory;
                    xmlFolder += "</span>\n";
                    Expant(cate.Idcategory, lCataBase, lLocaBase,ref xmlFolder);
                }                
            }
                        
            // add location            
            List<Location> lLocaChild = LocationDAO.getListLocationChild(idCategory,lLocaBase);
            if (lLocaChild.Count > 0)
            {
                if (bHasChild == false)
                {
                    xmlFiles += "<ul>\n";
                    bHasChild = true;
                }
                foreach (Location loca in lLocaChild)
                {
                    string link = "javascript:showMarket(" + loca.Idlocation.ToString() + "," + loca.Idcategory.ToString() + ",'" + loca.Name + "','" + loca.Address + "','" + loca.Description + "'," + loca.Latitude.ToString() + "," + loca.Longitude.ToString() + ")";
                    xmlFiles += "<li><span class=\"file\">";
                    xmlFiles += "<a href=\"" + link + "\">";
                    xmlFiles += loca.Name;
                    xmlFiles += "</a></span></li>\n";
                }                
            }
            if(bHasChild)
                xmlFiles += "</ul>\n";
            xmlFolder += xmlFiles + "</li>\n";
            xmlTree += xmlFolder;
        }
    }

}
